#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkRequest>
#include <QDebug>
#include <QMessageBox>
#include <QBuffer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , networkManager(new QNetworkAccessManager(this))
    , frameCount(0)
    , isConnected(false)
{
    ui->setupUi(this);

    // 设置默认URL
    ui->urlEdit->setText("http://192.168.99.196/");

    // 连接信号和槽
    connect(ui->connectButton, SIGNAL(clicked()), this, SLOT(onConnectClicked()));
    connect(ui->refreshButton, SIGNAL(clicked()), this, SLOT(onRefreshClicked()));

    // 创建FPS计算定时器
    fpsTimer = new QTimer(this);
    connect(fpsTimer, SIGNAL(timeout()), this, SLOT(updateFPS()));
    fpsTimer->start(1000); // 每秒更新一次FPS
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onConnectClicked()
{
    if (!isConnected) {
        cameraUrl = ui->urlEdit->text();
        if (cameraUrl.isEmpty()) {
            QMessageBox::warning(this, "警告", "请输入有效的URL地址");
            return;
        }

        qDebug() << "正在连接到:" << cameraUrl;
        ui->statusLabel->setText("正在连接...");

        // 创建新的网络请求
        QNetworkRequest request(cameraUrl);
        request.setHeader(QNetworkRequest::UserAgentHeader, "ESP32-CAM Viewer");
        request.setRawHeader("Accept", "multipart/x-mixed-replace");
        request.setRawHeader("Connection", "keep-alive");

        // 发送请求
        QNetworkReply *reply = networkManager->get(request);

        connect(reply, SIGNAL(readyRead()), this, SLOT(handleReadyRead()));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
                this, SLOT(handleError(QNetworkReply::NetworkError)));
        connect(reply, SIGNAL(finished()), this, SLOT(handleFinished()));

        isConnected = true;
        ui->connectButton->setText("断开");
        ui->statusLabel->setText("已连接");
    } else {
        // 断开连接
        QList<QNetworkReply*> replies = networkManager->findChildren<QNetworkReply*>();
        for (QNetworkReply* reply : replies) {
            reply->abort();
            reply->deleteLater();
        }

        isConnected = false;
        ui->connectButton->setText("连接");
        ui->statusLabel->setText("未连接");
        ui->imageLabel->setText("等待连接...");
    }
}

void MainWindow::handleReadyRead()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply) return;

    static QByteArray buffer;
    QByteArray newData = reply->readAll();
    qDebug() << "收到数据大小:" << newData.size() << "字节";
    buffer.append(newData);

    // 查找JPEG图像的起始和结束标记
    int startIndex = buffer.indexOf("\r\n\r\n");
    if (startIndex != -1) {
        startIndex += 4; // 跳过\r\n\r\n
        int endIndex = buffer.indexOf("\r\n--", startIndex);

        if (endIndex != -1) {
            QByteArray imageData = buffer.mid(startIndex, endIndex - startIndex);
            buffer = buffer.mid(endIndex); // 保留剩余数据

            QImage image = QImage::fromData(imageData);
            if (!image.isNull()) {
                qDebug() << "成功解码图像，大小:" << image.size();
                image = image.scaled(ui->imageLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
                ui->imageLabel->setPixmap(QPixmap::fromImage(image));
                frameCount++;
            } else {
                qDebug() << "图像解码失败";
            }
        }
    }
}

void MainWindow::handleError(QNetworkReply::NetworkError error)
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply) return;

    qDebug() << "网络错误:" << error << reply->errorString();
    ui->statusLabel->setText("连接错误: " + reply->errorString());
    isConnected = false;
    ui->connectButton->setText("连接");
}

void MainWindow::handleFinished()
{
    qDebug() << "连接已关闭";
    if (isConnected) {
        ui->statusLabel->setText("连接已断开");
        isConnected = false;
        ui->connectButton->setText("连接");
    }
}

void MainWindow::onRefreshClicked()
{
    if (isConnected) {
        onConnectClicked(); // 重新连接
    }
}

void MainWindow::updateFPS()
{
    ui->fpsLabel->setText(QString("FPS: %1").arg(frameCount));
    frameCount = 0;
}
